package com.garry.common.controller;

import com.garry.common.dto.LoginDto;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by GarryGe on 2016/11/30.
 */
@Controller
public class LoginController {

    @RequestMapping(value = "/loginpage",method = RequestMethod.GET)
    public String tologin(){
        return "/common/login";
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(LoginDto dto,Model model){
        UsernamePasswordToken token = new UsernamePasswordToken(dto.getUsername(), dto.getPassword());
        token.setRememberMe(true);
        try{
            SecurityUtils.getSubject().login(token);
        }catch (Exception e){
            model.addAttribute("error",e.getMessage());
            return "redirect:/loginpage";
        }
        return "homepage";
    }

    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logout(){
        //TODO
        System.out.println(SecurityUtils.getSubject().isAuthenticated());
        SecurityUtils.getSubject().logout();
        System.out.println(SecurityUtils.getSubject().isAuthenticated());

        return "homepage";
    }
}
